<?php

namespace app\admin\controller\goods;

use app\admin\controller\Controller;
use app\admin\model\goods\Category as CategoryModel;

/**
 * 商品分类
 * Class Category
 * @package app\admin\controller\goods
 */
class Category extends Controller
{
    protected $model;
    /**
     * 构造方法
     * @access public
     * @param  App  $app  应用对象
     */
    public function initialize()
    {
        parent::initialize();
        // 控制器初始化
        $this->model = new CategoryModel;
    }

    /**
     * 商品分类列表
     * @return array
     */
    public function index()
    {
        return $this->renderSuccess($this->model->getCacheTree());
    }

    /**
     * 删除商品分类
     * @param $category_id
     * @return array
     */
    public function delete($category_id)
    {
        if (!$this->model->remove($category_id)) {
            return $this->renderError($this->model->getError() ?? '删除失败');
        }
        return $this->renderSuccess('删除成功');
    }

    /**
     * 添加商品分类
     * @return array|mixed
     */
    public function add()
    {
        // 新增记录
        if ($this->model->add($this->request->only(['name','image_id','parent_id','sort']))) {
            return $this->renderSuccess([],'添加成功');
        }
        return $this->renderError($this->model->getError() ?? '添加失败');
    }

    /**
     * 编辑商品分类
     * @param $category_id
     * @return array
     */
    public function edit()
    {
        // 更新记录
        if ($this->model->edit($this->request->only(['name','image_id','parent_id','sort']))) {
            return $this->renderSuccess('','更新成功');
        }
        return $this->renderError($this->model->getError() ?? '更新失败');
    }

    /**
     * 商品分类
     * @param $category_id
     * @return array
     */
    public function detail()
    {
        $model = $this->model->get($this->request->param('category_id'), ['image']);
        // 获取所有地区
        $list = $this->model->getCacheTree();
        $this->renderSuccess(compact('list','model'));
    }

}
